import { Component, OnInit } from '@angular/core';
import { HttpClient } from '@angular/common/http';
// @ts-ignore
import { User } from './user';

const API_URL = '/api/users';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
  user: User[] | undefined;
  editingUser: null = null;
  users: any;

  constructor(private httpClient: HttpClient) {}

  ngOnInit(): void {
    this.getUsers();
  }

  getUsers(): void {
    this.httpClient.get<User[]>(API_URL).subscribe(users => {
      this.user = users;
    });
  }

  addUser(name: string, age: number, gender: string): void {
    const user = { name, age, gender } as User;
    this.httpClient.post(API_URL, user).subscribe(() => {
      this.getUsers();
    });
  }

  updateUser(user: User): void {
    this.httpClient.put(`${API_URL}/${user.id}`, user).subscribe(() => {
      this.editingUser = null;
      this.getUsers();
    });
  }

  deleteUser(user: User): void {
    this.httpClient.delete(`${API_URL}/${user.id}`).subscribe(() => {
      this.getUsers();
    });
  }
}
